package top.ivansong92.example.leetcode.learning.other;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class TestExample {

    /**
     * 202. 快乐数
     * @param n
     * @return
     */
    public boolean isHappy(int n) {
        if (n == 1) {
            return true;
        }
        Set<String> filter = new HashSet<>();
        boolean res = false;
        String s;
        char[] chars;
        int tmp = n, plus = 0;
        while (true) {
            s = tmp + "";
            if (filter.contains(s)) {
                break;
            }
            filter.add(s);
            chars = s.toCharArray();
            tmp = 0;
            for(char ch : chars) {
                plus = ch - '0';
                tmp += plus * plus;
            }

            if (tmp == 1) {
                res = true;
                break;
            }
        }
        return res;
    }

    public boolean isHappyV2(int n) {
        if (n == 1) {
            return true;
        }
        Set<Integer> filter = new HashSet<>();
        boolean res = false;
        int tmp = n, plus, k;
        while (true) {
            if (filter.contains(tmp)) {
                break;
            }
            filter.add(tmp);
            k = tmp;
            tmp = 0;
            while (k != 0) {
                plus = k % 10;
                tmp += plus * plus;
                k = (k - plus) / 10;
            }

            if (tmp == 1) {
                res = true;
                break;
            }
        }
        return res;
    }


    /**
     * 1005. K 次取反后最大化的数组和
     * @param nums
     * @param k
     * @return
     */
    public int largestSumAfterKNegations(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;
        if (len == 1) {
            return k % 2 == 0 ? nums[0] : -nums[0];
        }

        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if (k == 0 || nums[i] > 0) {
                break;
            }
            nums[i] = -nums[i];
            k--;
        }

        int res = 0;
        if (k % 2 == 0) {
            for (int n : nums) {
                res += n;
            }
            return res;
        }

        Arrays.sort(nums);
        nums[0] = -nums[0];
        for (int n : nums) {
            res += n;
        }

        return res;
    }
}
